package imgshare.service.impl;

import imgshare.common.api.ResultCode;
import imgshare.common.exception.ApiException;
import imgshare.mapper.FollowMapper;
import imgshare.mapper.UserMapper;
import imgshare.model.User;
import imgshare.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@CacheConfig(cacheNames = "users")
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FollowMapper followMapper;

    @Override
    public User findByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public User findByEmail(String email) {
        return userMapper.selectByEmail(email);
    }

    @Override
    public void createUser(User user) {
        int rowChanged = userMapper.insertSelective(user);
        if (rowChanged == 0) {
            throw new ApiException(ResultCode.SQL_ERROR);
        }
    }

    @Override
    public Boolean existByUsername(String username) {
        return userMapper.existByUsername(username);
    }

    @Override
    public Boolean existByEmail(String email) {
        return userMapper.existByEmail(email);
    }

    @CachePut(key = "#user.id")
    @Override
    public void update(User user) {
        int rowChanged = userMapper.updateByPrimaryKeySelective(user);
        if (rowChanged == 0) {
            throw new ApiException(ResultCode.SQL_ERROR);
        }
    }

    @Cacheable(key = "#id")
    @Override
    public User findOne(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<User> findAll() {
        return userMapper.selectAll();
    }

    @Override
    public List<User> findMyFollowingUsers(Integer userId) {
        return followMapper.selectBeFollowedUsersBySubjectId(userId);
    }
}
